/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.
 * <p/>
 * Author: newma
 * Date: 2015-6-24
 * Descript: 广告栏的
 * <p/>
 * Modified:
 */
package com.xysq.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xysq.lemon.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class XYBannerHelper {
    /**
     * 监听banner的图片被点击的事件
     */
    public interface OnItemClickListener {
        /**
         * 点击事件回调
         *
         * @param index: 被点击的图片列表位置
         * @param v:     被点击的图片（它是一个ImageView类）
         */
        public void onItemClick(int index, View v);
    }

    public static String IMAGE_CACHE_PATH = "imageloader/Cache"; // 图片缓存路径

    private static final int ROLL_IMAGE_INTERVAL = 4; // 自动滚动的时间间隔（单位为秒）
    private static final int MAX_DISCK_CACHE_SPACE = 32 * 1024 * 1024;
    private static final int MAX_CACHE_FILE_COUNT = 100; // 缓存图片的最大张数
    private static final int MAX_MEMORY_CACHE_SPACE = 12 * 1024 * 1024;

    private Activity m_activity;
    private int m_curItemIndex;
    private OnItemClickListener m_callback;

    private ViewPager m_viewPager;
    private BannerAdapter m_pageAdapter;

    private List<XYBannerInfo> m_bannerInfos;
    private List<View> m_dotViews;
    private List<ImageView> m_imgViews;
    private ArrayList<String> picUrlList = new ArrayList<>();

    // 异步加载图片
    private ImageLoader m_imageLoader;
    private DisplayImageOptions m_options;
    private Activity mActivity;

    private ScheduledExecutorService m_rollSchedule;    // 自动滚动定时器

    private Handler handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            m_viewPager.setCurrentItem(m_curItemIndex);
        }

        ;
    };

    public int getM_curItemIndex(){
        return m_curItemIndex;
    }

    public void destroyHelper() {
        m_rollSchedule.shutdown();
    }

    public XYBannerHelper(Activity activity) {
        this(activity, null);
    }

    public XYBannerHelper(Activity activity, List<XYBannerInfo> infos) {
        m_activity = activity;

        initImageLoader();

        if (infos == null) {
            m_bannerInfos = new ArrayList<XYBannerInfo>();
        } else {
            m_bannerInfos = infos;
        }
        initBannerPage();

        refreshBanner();
    }

    /**
     * 设置当banner中展示的图片被点击时需要被触发的回调函数
     *
     * @param cb: 回调函数
     */
    public void setOnItemClickCallback(OnItemClickListener cb) {
        m_callback = cb;
    }

    /**
     * 设置banner要显示的内容
     */
    public void setBannerInfo(List<XYBannerInfo> info) {
//		startAutoRoll();
        m_bannerInfos = info;

        m_curItemIndex = 0;
        refreshBanner();
    }

    /**
     * 开始自动滚动图片的功能
     */
    public void startAutoRoll() {
        m_rollSchedule = Executors.newSingleThreadScheduledExecutor();
        m_rollSchedule.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                synchronized (m_viewPager) {
                    m_curItemIndex = (m_curItemIndex + 1) % m_imgViews.size();
                    handler.obtainMessage().sendToTarget();
                }
            }
        }, ROLL_IMAGE_INTERVAL, ROLL_IMAGE_INTERVAL, TimeUnit.SECONDS);
    }

    /**
     * 停止自动滚动图片的功能
     */
    public void stopAutoRoll() {
        m_rollSchedule.shutdown();
    }

    @SuppressWarnings("deprecation")
    private void initBannerPage() {
        m_viewPager = (ViewPager) m_activity.findViewById(R.id.vpgBanner);
        m_pageAdapter = new BannerAdapter();
        m_viewPager.setAdapter(m_pageAdapter);
        m_viewPager.setOnPageChangeListener(new PageChangeListener());

        m_dotViews = new ArrayList<View>();
        m_imgViews = new ArrayList<ImageView>();
    }

    @SuppressLint("InflateParams")
    private void refreshBanner() {
        m_dotViews.clear();
        m_imgViews.clear();

        LinearLayout lly = (LinearLayout) m_activity.findViewById(R.id.llyDot);
        lly.removeAllViews();

        for (int i = 0; i < m_bannerInfos.size(); i++) {
            // 添加图片上的圆点
            LayoutInflater.from(m_activity).inflate(R.layout.xy_layout_banner_dot, lly);
            View dot = lly.getChildAt(i);
            if (m_curItemIndex == i) {
                dot.setBackgroundResource(R.drawable.xy_banner_dot_focused);
            }
            m_dotViews.add(dot);
            picUrlList.add(m_bannerInfos.get(i).getImgUrl());
            // 添加图片
            ImageView img = new ImageView(m_activity);
            m_imageLoader.displayImage(m_bannerInfos.get(i).getImgUrl(), img,
                    m_options);
            img.setScaleType(ScaleType.CENTER_CROP);
            m_imgViews.add(img);
        }

        m_pageAdapter.notifyDataSetChanged();
        m_viewPager.setCurrentItem(m_curItemIndex);
    }

    private void initImageLoader() {
//		File cacheDir = com.nostra13.universalimageloader.utils.StorageUtils
//				.getOwnCacheDirectory(m_activity.getApplicationContext(),
//						IMAGE_CACHE_PATH);
//
//		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
//				.cacheInMemory(true).cacheOnDisc(true).build();
//
//		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//				m_activity).defaultDisplayImageOptions(defaultOptions)
//				.memoryCache(new LruMemoryCache(MAX_MEMORY_CACHE_SPACE))
//				.memoryCacheSize(MAX_MEMORY_CACHE_SPACE)
//				.discCacheSize(MAX_DISCK_CACHE_SPACE).discCacheFileCount(MAX_CACHE_FILE_COUNT)
//				.discCache(new UnlimitedDiscCache(cacheDir))
//				.threadPriority(Thread.NORM_PRIORITY - 2)
//				.tasksProcessingOrder(QueueProcessingType.LIFO).build();

        m_imageLoader = ImageLoader.getInstance();
//		m_imageLoader.init(config);
        m_options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.def_img)
                .showImageForEmptyUri(R.drawable.def_img)
                .showImageOnFail(R.drawable.def_img)
                .cacheInMemory(true).cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .imageScaleType(ImageScaleType.EXACTLY).build();
    }

    /**
     * 这个函数可以被重载，当banner的图片改变时会调用此方法，在此方法内只需要更新相应的控件的内容就可以了
     *
     * @param curItemIndex: 改变后的图片位置
     * @param preItemIndex: 未改变前的图片位置
     * @param curItemInfo:  改变后的banner信息
     */
    protected void onBannerInfoChange(int curItemIndex, int preItemIndex, XYBannerInfo curItemInfo) {
        TextView title = (TextView) m_activity.findViewById(R.id.txt_title);
        if(TextUtils.isEmpty(curItemInfo.getTitle()) & title != null) {
            title.setText(curItemInfo.getTitle());
        }
    }

    /**
     * banner PageView的监听接口
     */
    private class PageChangeListener implements OnPageChangeListener {

        private int m_prePos = 0;

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                    //stopAutoRoll();	// 拖拉过程中，应该停止计时
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:
                    //startAutoRoll(); // 拖拉完后，要重新计时
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                default:
                    break;
            }
        }

        @Override
        public void onPageScrolled(int index, float scale, int pos) {

        }

        @Override
        public void onPageSelected(int position) {
            m_curItemIndex = position;
            XYBannerInfo bannerInfo = m_bannerInfos.get(position);
            XYBannerHelper.this.onBannerInfoChange(position, m_prePos, bannerInfo);

            m_dotViews.get(m_prePos).setBackgroundResource(R.drawable.xy_banner_dot_normal);
            m_dotViews.get(position).setBackgroundResource(R.drawable.xy_banner_dot_focused);
            m_prePos = position;
        }
    }

    /**
     * banner PageView的adapter
     */
    private class BannerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return m_bannerInfos.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imgView = m_imgViews.get(position);
            ((ViewPager) container).addView(imgView);

            imgView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (m_callback != null) {
						m_callback.onItemClick(position, v);
					}
/*                    Log.d("test","onclick");
                    Intent intent = new Intent(m_activity, ImagesActivity.class);
                    intent.putExtra(ImagesActivity.PARAM_CURRENT_POSITION, m_viewPager.getCurrentItem());
                    intent.putStringArrayListExtra(ImagesActivity.PARAM_IMAGE_URLS, picUrlList);
                    m_activity.startActivity(intent);*/
                }
            });
            return imgView;
        }

        @Override
        public void destroyItem(View view, int pos, Object obj) {
            ((ViewPager) view).removeView((View) obj);
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }
    }
}
